package com.example.service;

import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 数据保存服务
 * 职责：处理爬取数据的保存
 * 功能：
 * - 初始化数据文件
 * - 保存爬取的数据
 * - CSV格式处理
 * - 文件资源管理
 */
@Component
public class DataSaver {
    
    private final ContentExtractor contentExtractor;
    private BufferedWriter writer;

    public DataSaver(ContentExtractor contentExtractor) {
        this.contentExtractor = contentExtractor;
    }

    /**
     * 初始化写入器
     */
    public void initWriter(String savePath) throws IOException {
        // 创建目录
        File file = new File(savePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            System.out.println("创建目录: " + parentDir.getAbsolutePath());
            if (!parentDir.mkdirs()) {
                throw new IOException("无法创建目录: " + parentDir.getAbsolutePath());
            }
        }

        // 创建文件
        if (!file.exists()) {
            System.out.println("创建文件: " + file.getAbsolutePath());
            if (!file.createNewFile()) {
                throw new IOException("无法创建文件: " + file.getAbsolutePath());
            }
        }

        writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(file, true), StandardCharsets.UTF_8));
        
        // 如果文件为空，写入CSV头
        if (file.length() == 0) {
            writer.write("标题,内容,来源URL,时间戳\n");
        }
    }

    /**
     * 保存数据
     */
    public void saveData(String title, String content, String url) throws IOException {
        if (writer == null) {
            throw new IllegalStateException("Writer未初始化");
        }

        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        writer.write(String.format("%s,%s,%s,%s\n",
                escapeCsv(title),
                escapeCsv(content),
                escapeCsv(url),
                timestamp));
        writer.flush();
    }

    /**
     * CSV转义
     */
    private String escapeCsv(String value) {
        if (value == null) return "";
        return value.contains(",") || value.contains("\"") || value.contains("\n") ?
                "\"" + value.replace("\"", "\"\"") + "\"" : value;
    }

    /**
     * 关闭写入器
     */
    public void closeWriter() {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                System.err.println("关闭写入器失败: " + e.getMessage());
            }
        }
    }
} 